<?php
namespace app\common\model\users;

use think\Model;
use think\Db;
use think\Session;
use app\common\model\base\CommonModel;
use app\common\model\users\UsersAccess;
use app\common\model\tools\Smsbao;


/*************************************************
 *ClassName:     Users
 *Description:   用户类（通用）
 *Others:
 *************************************************/

class Users extends CommonModel
{
    //设置表名
    static $table_name = 'users';
    /**
     * getWhere 得到用户id的where条件（私有方法）
     * @karl
     * @DateTime 2017-05-23T21:58:07+0800
     * @param    string     $user_var       用户标识（可能是uid/mobile/username/email）
     * @return   array      $where 数组
     */
    static private function getWhere($user_var)
    {
        $email_pattern = "/([\w\-]+\@[\w\-]+\.[\w\-]+)/";
        $mobile_pattern = "/^1[34578]\d{9}$/";
        $num_pattern = "/^\d*$/";
        $where = [];
        if (preg_match($num_pattern, $user_var)) {
            if (preg_match($mobile_pattern, $user_var)) {
                //手机号
                $where['mobile'] = $user_var;
            } else {
                //uid
                $where['uid'] = $user_var;
            }
        } elseif(preg_match($email_pattern, $user_var)) {
            //邮箱
            $where['email'] = $user_var;
        } else {
            //用户名
            $where['username'] = $user_var;
        }
        return $where;
    }
    /**
     * getUid 得到用户id
     * @karl
     * @DateTime 2017-05-23T21:58:07+0800
     * @param    string     $user_var       用户标识（可能是uid/mobile/username/email）
     * @return   array      [error_code, error_msg, uid]
     */
    static public function getUid($user_var)
    {
        $result = ['error_code' => 0, 'error_msg' => ""];
        $where = self::getWhere($user_var);
        $user_info = Db::name('users')->where($where)->find();
        if ($uid = $user_info['uid']) {
            $result['uid'] = $uid;
            $result['username'] = $user_info['username'];
        } else {
            $result = ['error_code' => 1, 'error_msg' => "查询不到相关用户uid"];
        }
        return $result;
    }
    /**
     * getUserInfoByUid 通过uid获得用户信息
     * @param    int        $uid
     * @return   array      [error_code, error_msg, data]
     */
    static public function getUserInfoByUid($uid)
    {
        $where = ['uid' => $uid];
        return self::getOneRow($where);
    }
    /**
     * getUserInfoByPassword 通过用户密码获取用户信息
     * @karl
     * @DateTime 2017-04-05T21:58:07+0800
     * @param    string     $user_var       用户标识（可能是uid/mobile/username/email）
     * @param    string     $password       密码
     * @param    string     $role           用户角色     
     * @return   array      [error_code, error_msg, data]
     */
    static public function getUserInfoByPassword($user_var, $password, $role = '')
    {
        $where = self::getWhere($user_var);
        $where['password'] = md5($password);
        if (!empty($role)) $where['role'] = $role;
        $user_info = Db::name('users')->where($where)->find();
        //去除一些用户敏感数据
        unset($user_info['password']);
        if($user_info) {
            $result['error_code'] = 0;
            $result['error_msg'] = '';
            $result['data'] = $user_info;
        } else {
            $result['error_code'] = 1;
            $result['error_msg'] = '用户标识和密码不正确';
        }
        return $result;
    }
    /**
     * login 用户登陆
     * 支持多角色登陆，设置$role，与user表role字段对应
     * 会话类型支持，自定义access方式（UsersAccess类）和thinkphp的session方式
     * @karl
     * @DateTime 2017-04-14T11:00:15+0800
     * @param    string                   $user_var （可能是uid/mobile/username/email）
     * @param    string                   $password 密码
     * @param    string                   $role 角色
     * @param    string                   $type 会话类型 acesss方式和session方式
     * @return   array                    [error_code, error_msg, data=> []]
     */
    static public function login($user_var, $password, $role = "customer", $type = "access")
    {
        $check_info = Users::getUserInfoByPassword($user_var, $password, $role);
        if ($check_info['error_code'] == 0) {
            //得到uid
            $uid = $check_info['data']['uid'];
            //登陆为access方式
            if ($type == "access") { 
                $access_info = UsersAccess::createAccess($uid);
                if ($access_info['error_code'] == 0) {
                    $access_data['user_info'] = $check_info['data'];
                    $save_access_info = UsersAccess::saveAccessValue($access_info['data']['access_token'], $access_data);
                    $check_info['data']['access_token'] = $access_info['data']['access_token'];
                    if ($save_access_info['error_code'] == 0) {
                        return $check_info;
                    } else {
                        return $save_access_info;
                    }
                } else {
                    return $access_info;
                }
            //登陆为session方式
            } elseif($type == "session") {
                session('user_info', $check_info);
                $result = ['error_code' => 0, 'error_msg' => "",'data'=>$check_info['data']];
            } else {
                return ['error_code' => 3, 'error_msg' => "type参数不正确"];
            }
        } else {
            $result = ['error_code' => 1, 'error_msg' => "登陆失败"];
        }
        return $result;
    }
    /**
     * register 用户注册
     * @karl
     * @DateTime 2017-04-14T11:05:31+0800
     * @param    array                      $user_data 用户信息
     * @return   array                      [error_code, error_msg, uid]
     */
    static public function register($user_data)
    {
        //获取parentUid
        if(isset($user_data['invitation_code'])) {
            $user_data['parent'] = self::getParentByInvitation($user_data['invitation_code']);
        }
        $user_data['password'] = md5($user_data['password']);
        unset($user_data['invitation_code']);
        $user_data['role'] = 'customer';
        $user_data['create_time'] = time();
        return self::add($user_data);
    }
    /**
     * getParentByInvitation 得到父级uid
     * @karl
     * @DateTime 2017-04-14T11:05:31+0800
     * @param    string                      $invitation_code 邀请码
     * @return   array                      [error_code, error_msg, uid]
     */
    static public function  getParentByInvitation($invitation_code)
    {
        $where['invitation_code'] = $invitation_code;
        $user_info = Db::name('users')->where($where)->find();
        $uid = 0;
        if ($user_info)
            $uid = $user_info['uid'];
        return $uid;
    }
    /**
     * changePassword 修改密码
     * @karl
     * @DateTime 2017-04-18T06:20:42+0800
     * @param    int                      $uid          用户id
     * @param    string                   $old_password 原密码
     * @param    string                   $new_password 新密码
     * @return   array                    [error_code, error_msg]
     */
    static public function changePassword($uid, $old_password, $new_password) 
    {
        $result = ['error_code' => 0, 'error_msg' => ""];
        $check_pass_info = self::getUserInfoByPassword($uid, $old_password);
        if ($check_pass_info['error_code'] != 0) {
            return $check_pass_info;
        }
        $where['uid'] = $uid;
        $data['password'] = md5($new_password);
        return self::edit($where, $data);
    }
    /**
     * getParentId 得到父级uid
     * @xiao
     * @DateTime 2016-11-27T21:47:40+0800
     * @param    int                   $uid
     * @return   array                 [error_code, error_msg, pid]
     */
    static public function getParentId($uid)
    {   
        $where['uid'] = $uid;
        $res = Db::name(self::$table_name)->where($where)->find();
        if ($res) {
            $result['error_code'] = 0;
            $result['error_msg'] = '';
            $result['pid'] = $res['parent'];
        }else{
            $result['error_code'] = 1;
            $result['error_msg'] = '查询失败';
        }
        return $result;
    }
    /**
     * getChildren 得到指定级子uid
     * @xiao
     * @DateTime 2016-11-27T21:49:55+0800
     * @param    integer                  $uid[] = ['uid'=> 'uid'];
     * @param    integer                  $level 第几级
     * @return   array [[0]=>str,[1]=>str] 等级-1 => str='uid,uid,uid';字符
     */
    static public function getChildren($uid, $level = 1)
    {
        static $count=0;
        static $result = [];
        if ($uid) {
            $arr = array();
            foreach ($uid as $v) {
                $where['parent'] = $v['uid'];
                $res = Db::name(self::$table_name)->where($where)->select();
                $result['data'][$count] = $res;
                if ($res) {
                    foreach ($res as $key => $v) {
                        $arr[] = ['uid' => $v['uid']];
                        $str[] = $v['uid'];
                    }
                    $result[$count] = implode(',',$str);
                }
            }
            $count++;
            if ($count < $level ) {
                self::getChildren($arr, $level);
            }
        }
        return $result;
    }
    /**
     * updateBalance 更新余额
     * @karl
     * @DateTime 2017-04-05T21:58:07+0800
     * @param    int        $uid 用户id
     * @return   array      [error_code, error_msg, balance]
     */
    static public function updateBalance($uid)
    {
        $result = ['error_code' => 0, 'error_msg' => ''];
        $balance_return = UsersMoney::getBalance($uid);
        if ($balance_return['error_code'] == 0) {
            $balance = $balance_return['balance'];
            Db::name(self::$table_name)->where(['uid' => $uid])->update(['balance' => $balance]);
        } else {
            return $balance_return;
        }
    }

}

?>